package com.da.orderPojo.service.impl;

import com.da.orderPojo.Order;
import com.da.orderPojo.service.OrderService;
import com.da.productPojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * TODO
 *
 * @Author chen
 * @Date 2025/8/6 17:05
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @Override
    public Order createOrder(Long userId, Long productId) {

        //获取订单商品信息
        Product product = getProductFromRemote(productId);
        Order order = new Order();
        order.setId(1l);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setProductId(productId);
        order.setNickName("张三");
        order.setAddress("上海");
        order.setProductList(Arrays.asList(product));
        return order;
    }

    /**
     * 远程获取商品信息
     * @param productId
     * @return
     */
    private Product getProductFromRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/getProductById/" + productId;
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
